package top.luo.config;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import top.luo.pojo.Configuration;
import top.luo.pojo.MappedStatement;

import java.io.InputStream;
import java.util.List;

/**
 * @author luo
 * @date 2021-01-04 21:30
 */
public class XmlMapperBuilder {

    private final Configuration configuration;

    public XmlMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    @SuppressWarnings("unchecked")
    public void parse(InputStream ins) throws DocumentException {
        Document document = new SAXReader().read(ins);
        Element root = document.getRootElement();

        String namespace = root.attributeValue("namespace");

        List<Element> selectList = root.selectNodes("//select");

        MappedStatement mappedStatement;
        for (Element selectElement : selectList) {
            mappedStatement = new MappedStatement();

            mappedStatement.setId(selectElement.attributeValue("id"));
            mappedStatement.setResultType(selectElement.attributeValue("resultType"));
            mappedStatement.setParameterType(selectElement.attributeValue("parameterType"));
            mappedStatement.setSql(selectElement.getTextTrim());

            configuration.getMappedStatementMap().put(namespace + "." + mappedStatement.getId(), mappedStatement);
        }

    }

}
